package com.advertisementsystem.Servie.Impl;

import com.advertisementsystem.Dto.LoginUser;
import com.advertisementsystem.Dto.RegisterDTO;
import com.advertisementsystem.Dto.UserQueryDTO;
import com.advertisementsystem.Dto.UserUpdateDTO;
import com.advertisementsystem.Enum.RoleTypeEnum;
import com.advertisementsystem.Exception.BusinessException;
import com.advertisementsystem.Mapper.UserMapper;
import com.advertisementsystem.Mapper.UserRoleMapper;
import com.advertisementsystem.Servie.UserService;
import com.advertisementsystem.entity.User;
import com.advertisementsystem.Exception.ResponseResult;
import com.advertisementsystem.entity.UserRole;
import com.advertisementsystem.vo.UserInfoVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRoleMapper userRoleMapper;
    @Override
    public ResponseResult<?> register(RegisterDTO registerDTO) {
        log.info("用户注册开始: {}", registerDTO);
        // 1. 参数校验
        if (!registerDTO.getPassword().equals(registerDTO.getConfirmPassword())) {
            return ResponseResult.error(HttpStatus.BAD_REQUEST.value(), "两次输入的密码不一致");
        }

        // 2. 检查用户名是否已存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, registerDTO.getUsername());
        Long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            return ResponseResult.error(HttpStatus.BAD_REQUEST.value(), "用户名已存在");
        }
        User user = new User();
        UserRole userRole = new UserRole();

        if (Objects.equals(registerDTO.getRole(), "advertiser"))
        {
             user.setRoleType(RoleTypeEnum.ADVERTISER.getCode());

            userRole.setRoleId(2L);

        }
        if (Objects.equals(registerDTO.getRole(), "device_owner"))
        {
            userRole.setRoleId(3L);
            user.setRoleType(RoleTypeEnum.DEVICE_OWNER.getCode());
        }
        // 3. 创建用户对象

        user.setUsername(registerDTO.getUsername());
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));

        user.setCreatedTime(LocalDateTime.now());

        user.setUpdatedTime(LocalDateTime.now());

        // 4. 保存用户
        try {
            userMapper.insert(user);
            userRole.setUserId(user.getId());
            userRole.setCreatedTime(LocalDateTime.now());
            userRoleMapper.insert(userRole);

            log.info("用户注册成功: {}", user.getUsername());

            // 5. 返回成功响应
            return ResponseResult.success("注册成功");
        } catch (Exception e) {
            log.error("用户注册失败: {}", e.getMessage(), e);
            throw new RuntimeException("注册失败，请稍后重试");
        }
    }

    @Override
    public ResponseResult<?> updateUserInfo(UserUpdateDTO userUpdateDTO) {
        // 1. 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        Long userId = loginUser.getUser().getId();

        // 2. 构建更新对象
        User user = new User();
        user.setId(userId);

        // 3. 设置要更新的字段
        if (StringUtils.hasText(userUpdateDTO.getNickname())) {
            user.setNickname(userUpdateDTO.getNickname());
        }
        if (StringUtils.hasText(userUpdateDTO.getEmail())) {
            user.setEmail(userUpdateDTO.getEmail());
        }
        if (StringUtils.hasText(userUpdateDTO.getPhone())) {
            user.setPhone(userUpdateDTO.getPhone());
        }
        if (StringUtils.hasText(userUpdateDTO.getAvatar()))
        {
            user.setAvatar(userUpdateDTO.getAvatar());
        }
        user.setUpdatedTime(LocalDateTime.now());

        // 4. 处理密码更新
        if (StringUtils.hasText(userUpdateDTO.getNewPassword())) {
            if (!userUpdateDTO.getNewPassword().equals(userUpdateDTO.getConfirmPassword())) {
                return ResponseResult.error(HttpStatus.BAD_REQUEST.value(), "两次输入的密码不一致");
            }
            user.setPassword(passwordEncoder.encode(userUpdateDTO.getNewPassword()));
        }

        // 5. 更新用户信息
        try {
            // 只更新非null字段
            userMapper.updateById(user);
            // 6. 如果更新成功，更新SecurityContext中的用户信息
            User updatedUser = userMapper.getUserById(userId);
            LoginUser newLoginUser = new LoginUser(updatedUser, loginUser.getPermissions());
            Authentication newAuth = new UsernamePasswordAuthenticationToken(
                    newLoginUser,
                    null,
                    newLoginUser.getAuthorities()
            );
            SecurityContextHolder.getContext().setAuthentication(newAuth);

            log.info("用户信息更新成功: {}", userId);
            return ResponseResult.success("更新成功");
        } catch (Exception e) {
            log.error("用户信息更新失败: {}", e.getMessage(), e);
            throw new RuntimeException("更新失败，请稍后重试");
        }
        }

    @Override
    public ResponseResult<UserInfoVO> getUserInfo() {
        // 1. 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        Long userId = loginUser.getUser().getId();

        // 2. 查询用户详细信息
        User user = userMapper.getUserById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 3. 转换为VO对象
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setId(user.getId());
        userInfoVO.setUsername(user.getUsername());
        userInfoVO.setNickname(user.getNickname());
        userInfoVO.setEmail(user.getEmail());
        userInfoVO.setPhone(user.getPhone());
        userInfoVO.setRoleType(user.getRoleType());
        userInfoVO.setStatus(user.getStatus());
        userInfoVO.setCreatedTime(user.getCreatedTime());
        userInfoVO.setAvatar(user.getAvatar()==null?"":user.getAvatar());
        // 设置角色类型名称
        userInfoVO.setRoleTypeName(RoleTypeEnum.getNameByCode(user.getRoleType()));

        // 设置状态名称
        userInfoVO.setStatusName(user.getStatus() != null && user.getStatus() == 1 ? "启用" : "禁用");

        return ResponseResult.success(userInfoVO);
    }

    @Override
    public User createUser(User user) {
        // 检查用户名是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        if (userMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("用户名已存在");
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setCreatedTime(LocalDateTime.now());
        user.setUpdatedTime(LocalDateTime.now());
        user.setStatus(1); // 默认启用

        userMapper.insert(user);
        return user;
    }


    @Override
    public User updateUser(User user) {
        User existingUser = userMapper.getUserById(user.getId());
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }

        user.setUpdatedTime(LocalDateTime.now());
        user.setPassword(null); // 更新用户信息时不更新密码

        userMapper.updateById(user);
        return user;
    }


    @Override
    public boolean deleteUser(Long id) {
        return userMapper.deleteById(id) > 0;
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.getUserById(id);
    }


    @Override
    public Page<User> listUsers(UserQueryDTO queryDTO) {
        Page<User> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        queryWrapper.like(StringUtils.hasText(queryDTO.getUsername()), User::getUsername, queryDTO.getUsername())
                .like(StringUtils.hasText(queryDTO.getNickname()), User::getNickname, queryDTO.getNickname())
                .like(StringUtils.hasText(queryDTO.getPhone()), User::getPhone, queryDTO.getPhone())
                .like(StringUtils.hasText(queryDTO.getEmail()), User::getEmail, queryDTO.getEmail())
                .eq(queryDTO.getStatus() != null, User::getStatus, queryDTO.getStatus())
                .eq(queryDTO.getRoleType() != null, User::getRoleType, queryDTO.getRoleType())
                .orderByDesc(User::getCreatedTime);

        return userMapper.selectPage(page, queryWrapper);
    }
    @Override
    public boolean updateUserStatus(Long id, Integer status) {
        User user = new User();
        user.setId(id);
        user.setStatus(status);
        user.setUpdatedTime(LocalDateTime.now());
        return userMapper.updateById(user) > 0;
    }


    @Override
    public boolean updatePassword(Long id,  String newPassword) {
        User user = userMapper.getUserById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }


        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setPassword(passwordEncoder.encode(newPassword));
        updateUser.setUpdatedTime(LocalDateTime.now());

        return userMapper.updateById(updateUser) > 0;
    }

    @Override
    public IPage<User> page(Page<User> page, LambdaQueryWrapper<User> queryWrapper) {
        return userMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<Long> getUserIdsByRoleId(Long roleId) {
        return userMapper.selectUserIdsByRoleId(roleId);
    }

    @Override
    public List<Long> getAllUserIds() {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        // 只查询ID字段
        queryWrapper.select(User::getId);

        List<User> users = userMapper.selectList(queryWrapper);
        return users.stream().map(User::getId).collect(Collectors.toList());
    }

    @Override
    public User getUserByUsername(String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        return userMapper.selectOne(queryWrapper);
    }

}

